<template>
  <div class="csg-date">
    <div class="csg-date__input-wrapper" @click="toggleCalendar">
      <input
        type="text"
        class="csg-date__input"
        :value="formattedDate"
        readonly
        placeholder="选择日期"
        @blur="handleBlur"
      />
      <span class="csg-date__icon">
        <i class="iconfont icon-calendar"></i>
      </span>
    </div>

    <div class="csg-date__calendar" v-show="isCalendarVisible" @click.stop>
      <div class="csg-date__calendar-header">
        <button class="csg-date__nav-button" @click="prevMonth">&lt;</button>
        <span class="csg-date__month-year">{{ currentMonthYear }}</span>
        <button class="csg-date__nav-button" @click="nextMonth">&gt;</button>
      </div>
      <div class="csg-date__calendar-weekdays">
        <div v-for="day in weekdays" :key="day" class="csg-date__weekday">
          {{ day }}
        </div>
      </div>
      <div class="csg-date__calendar-days">
        <div
          v-for="day in daysInMonth"
          :key="day.date"
          class="csg-date__day"
          :class="{
            'csg-date__day--selected': isSelected(day.date),
            'csg-date__day--today': isToday(day.date),
            'csg-date__day--other-month': !day.isCurrentMonth,
          }"
          @click="selectDate(day.date)"
        >
          {{ day.day }}
        </div>
      </div>
      <!-- 时间选择部分 -->
      <div class="csg-date__time-selector" v-if="valueType === 'datetime'">
        <div class="csg-date__time-selector-item">
          <select v-model="hours" @change="updateTime">
            <option v-for="h in 24" :value="h - 1" :key="h">
              {{ String(h - 1).padStart(2, '0') }}
            </option>
          </select>
          <span>时</span>
        </div>
        <div class="csg-date__time-selector-item">
          <select v-model="minutes" @change="updateTime">
            <option v-for="m in 60" :value="m - 1" :key="m">
              {{ String(m - 1).padStart(2, '0') }}
            </option>
          </select>
          <span>分</span>
        </div>
        <div class="csg-date__time-selector-item">
          <select v-model="seconds" @change="updateTime">
            <option v-for="s in 60" :value="s - 1" :key="s">
              {{ String(s - 1).padStart(2, '0') }}
            </option>
          </select>
          <span>秒</span>
        </div>
      </div>

      <!-- 新增按钮区域 -->
      <div class="csg-date__footer">
        <csg-button
          class="csg-date__button csg-date__button--clear"
          @click="clearDate"
        >
          清除
        </csg-button>
        <csg-button
          class="csg-date__button csg-date__button--confirm"
          @click="confirmDate"
        >
          确定
        </csg-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import csgButton from '../csgButton/index.vue';

const hours = ref(0);
const minutes = ref(0);
const seconds = ref(0);

const props = defineProps({
  modelValue: {
    type: Date,
    default: null,
  },
  valueType: {
    type: String,
    default: 'date', // 'date'或'datetime'
    validator: (value) => ['date', 'datetime'].includes(value),
  },
});

const emit = defineEmits(['update:modelValue', 'change']);

watch(
  () => props.modelValue,
  (newVal) => {
  
    if (newVal) {
      hours.value = newVal.getHours();
      minutes.value = newVal.getMinutes();
      seconds.value = newVal.getSeconds();
    }
  }
);



const currentDate = ref(props.modelValue || new Date());
const isCalendarVisible = ref(false);

const formattedDate = computed(() => {
  if (!props.modelValue) return new Date().toLocaleDateString('zh-CN');
  return props.modelValue.toLocaleDateString('zh-CN');
});

const currentMonthYear = computed(() => {
  return currentDate.value.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
  });
});
const updateTime = () => {
  if (!props.modelValue) return;

  const newDate = new Date(props.modelValue);
  newDate.setHours(hours.value);
  newDate.setMinutes(minutes.value);
  newDate.setSeconds(seconds.value);

  emit('update:modelValue', newDate);
  emit('change', formatDate(newDate, props.valueType));
};

// 新增日期格式化函数
const formatDate = (date, type) => {
  if (isNaN(date.getTime())) return '无效日期';

  if (type === 'datetime') {
    return date
      .toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
      })
      .replace(/\//g, '-');
  } else {
    return date.toLocaleDateString('zh-CN').replace(/\//g, '-');
  }
};

const weekdays = ['日', '一', '二', '三', '四', '五', '六'];

const daysInMonth = computed(() => {
  const year = currentDate.value.getFullYear();
  const month = currentDate.value.getMonth();
  const firstDay = new Date(year, month, 1);
  const lastDay = new Date(year, month + 1, 0);
  const days = [];

  // 上个月的最后几天
  const prevMonthDays = firstDay.getDay();
  for (let i = prevMonthDays - 1; i >= 0; i--) {
    const date = new Date(year, month, -i);
    days.push({
      day: date.getDate(),
      date,
      isCurrentMonth: false,
    });
  }

  // 当前月的天数
  for (let i = 1; i <= lastDay.getDate(); i++) {
    const date = new Date(year, month, i);
    days.push({
      day: i,
      date,
      isCurrentMonth: true,
    });
  }

  // 下个月的前几天
  const nextMonthDays = 42 - days.length;
  for (let i = 1; i <= nextMonthDays; i++) {
    const date = new Date(year, month + 1, i);
    days.push({
      day: i,
      date,
      isCurrentMonth: false,
    });
  }

  return days;
});

const toggleCalendar = () => {
  isCalendarVisible.value = !isCalendarVisible.value;
};

const handleBlur = () => {
  setTimeout(() => {
    // isCalendarVisible.value = false;
  }, 200);
};

const prevMonth = () => {
  currentDate.value = new Date(
    currentDate.value.getFullYear(),
    currentDate.value.getMonth() - 1,
    1
  );
};

const nextMonth = () => {
  currentDate.value = new Date(
    currentDate.value.getFullYear(),
    currentDate.value.getMonth() + 1,
    1
  );
};

const isSelected = (date) => {
  return (
    props.modelValue &&
    date.getDate() === props.modelValue.getDate() &&
    date.getMonth() === props.modelValue.getMonth() &&
    date.getFullYear() === props.modelValue.getFullYear()
  );
};

const isToday = (date) => {
  const today = new Date();
  return (
    date.getDate() === today.getDate() &&
    date.getMonth() === today.getMonth() &&
    date.getFullYear() === today.getFullYear()
  );
};

const selectDate = (date) => {
  emit('update:modelValue', date);
};

const confirmDate = () => {
  updateTime();
  isCalendarVisible.value = false;
  
};

const clearDate = () => {
  emit('update:modelValue', new Date());
  emit('change', new Date());
  hours.value = 0;
  minutes.value = 0;
  seconds.value = 0;
};
</script>

<style lang="scss" scoped>
.csg-date {
  position: relative;
  display: inline-block;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  width: 220px;

  &__input-wrapper {
    position: relative;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    transition: border-color 0.3s ease;
    cursor: pointer;

    &:hover {
      border-color: #c0c4cc;
    }
  }

  &__input {
    width: 100%;
    padding: 8px 30px 8px 12px;
    border: none;
    outline: none;
    font-size: 14px;
    color: #606266;
    background: transparent;
    cursor: pointer;
  }

  &__icon {
    position: absolute;
    right: 8px;
    top: 50%;
    transform: translateY(-50%);
    color: #c0c4cc;
    transition: color 0.3s ease;
  }

  &__calendar {
    position: absolute;
    top: 100%;
    left: 0;
    margin-top: 5px;
    width: 240px;
    background: #fff;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    z-index: 1000;
    padding: 10px;
  }

  &__calendar-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    font-size: 14px;
  }

  &__nav-button {
    background: none;
    border: none;
    cursor: pointer;
    padding: 0 10px;
    font-size: 16px;
    color: #606266;

    &:hover {
      color: #409eff;
    }
  }

  &__calendar-weekdays {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    text-align: center;
    margin-bottom: 10px;
    font-size: 12px;
    color: #909399;
  }

  &__calendar-days {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    gap: 4px;
  }
  &__time-selector {
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
    padding-top: 10px;
    border-top: 1px solid #ebeef5;
  }

  &__time-selector-item {
    display: flex;
    align-items: center;

    select {
      width: 60px;
      padding: 5px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      outline: none;
      color: #606266;
      cursor: pointer;
      transition: border-color 0.3s;
      /* 隐藏滚动条 */
      &::-webkit-scrollbar {
        display: none;
      }
      &:hover {
        border-color: #c0c4cc;
      }

      &:focus {
        border-color: #409eff;
      }
    }

    span {
      margin-left: 5px;
      font-size: 12px;
      color: #909399;
    }
  }

  &__day {
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    cursor: pointer;
    border-radius: 4px;

    &:hover {
      background-color: #f5f7fa;
    }

    &--selected {
      background-color: #409eff;
      color: #fff;

      &:hover {
        background-color: #409eff;
      }
    }

    &--today {
      color: #409eff;
      font-weight: bold;
    }

    &--other-month {
      color: #c0c4cc;
    }
  }
  &__footer {
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
    padding-top: 10px;
    border-top: 1px solid #ebeef5;
  }

  &__button {
    flex: 1;
    padding: 6px 12px;
    border-radius: 4px;
    font-size: 12px;
    cursor: pointer;
    transition: all 0.3s;

    &--clear {
      margin-right: 8px;
      background-color: #f5f5f5;
      color: green;
      border: 1px solid #dcdfe6;

      &:hover {
        background-color: #e9e9e9;
      }
    }

    &--confirm {
      background-color: #409eff;
      color: #fff;
      border: 1px solid #409eff;

      &:hover {
        background-color: #66b1ff;
      }
    }
  }
}
</style>
